// 第一步：切换显示和隐藏属性，针对小图、大图
// 第二步：把移动事件绑定给小图，焦点focus也跟随鼠标位置进行移动
// 第三步：大图移动与小图一致，用百分比

class Magnifier{
    // 获取时间元素
    constructor(){
        this.small_img_ele = document.querySelector(".main-left");
        this.big_img_ele = document.querySelector(".big-img");
        // 获取大图里面的图片
        this.big_img = document.querySelector(".big-img img");

        this.focus_ele = document.querySelector(".focus");

        this.mainbox_ele = document.querySelector(".mainbox");

        this.mainbox_offset = {
            left : this.mainbox_ele.offsetLeft ,
            top : this.mainbox_ele.offsetTop
        }  
        // 获取到焦点框的宽度，要减去一半，时鼠标出现在焦点的正中间
        this.focus_size = {
            width : parseInt(getComputedStyle(this.focus_ele).width),
            height: parseInt(getComputedStyle(this.focus_ele).height)
        }
    }
    // 绑定事件
    bindEvent(){
        // 设置存储实例对象
        var tab = this ;
        // 鼠标移入显示
        this.small_img_ele.addEventListener( "mouseover" ,  function(){
            tab.toggle("show")
        })
        // 鼠标移出隐藏
        this.small_img_ele.addEventListener( "mouseout" ,  function(){
            tab.toggle("hide")
        })
        // 鼠标移动事件
        this.small_img_ele.addEventListener( "mousemove" , function( event ){
            tab.focusMove( event.clientX , event.clientY );
            
            // 大图移动与焦点移动显示内容一致
            tab.bigImgMove()

        })
    }
    // 切换显示和隐藏
    toggle( type ){
        switch (type) {
            case "show":
                this.big_img_ele.style.display = "block";
                this.focus_ele.style.display = "block";
                break;
            case "hide":
                this.big_img_ele.style.display = "none";
                this.focus_ele.style.display = "none";
                break;
        }

    }
    // 鼠标移动事件
    focusMove( x , y ){
        var _left = x - this.mainbox_offset.left - this.focus_size.width / 2 ;
        var _top = y - this.mainbox_offset.top - this.focus_size.height / 2 ;
        // 边界检测
        if( _left<0){
            _left = 0
        }
        if( _top < 0 ){
            _top = 0
        }
        if( _left > 250){
            _left = 250
        }
        if( _top > 250){
            _top = 250
        }
        this.focus_ele.style.left = _left + "px" ;
        this.focus_ele.style.top  = _top  + "px" ;

        // 移动百分比
        this.prop_left = _left / 250 ;
        this.prop_top  = _top  / 250 ;
    }
    // 放大图移动事件
    bigImgMove(){
        this.big_img.style.left = -this.prop_left * 875 + "px" ;
        this.big_img.style.top  = -this.prop_top * 875 + "px"
    }
}
var glass = new Magnifier();
glass.bindEvent();